/**
 * Copyright (C) 2016 Hyphenate Inc. All rights reserved.
 * <p/>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.xcjw.com.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMCursorResult;
import com.hyphenate.chat.EMGroupInfo;
import com.hyphenate.exceptions.HyphenateException;
import com.xcjw.com.R;

import java.util.ArrayList;
import java.util.List;

public class PublicGroupsActivity extends BaseActivity {
      private ProgressBar pb;
      private ListView listView;
      private GroupsAdapter adapter;

      private List<EMGroupInfo> groupsList;
      private List<EMGroupInfo> alist;
      private List<EMGroupInfo> allist;
      private boolean isLoading;
      private boolean isFirstLoading = true;
      private boolean hasMoreData = true;
      private String cursor;
      private final int pagesize = 20;
      private LinearLayout footLoadingLayout;
      private ProgressBar footLoadingPB;
      private TextView footLoadingText;
      private Button searchBtn;
      private EditText searchtex;
      private ListView listViews;
      private GroupsAdapter adapters;


      @Override
      protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.em_activity_public_groups);
            pb = (ProgressBar) findViewById(R.id.progressBar);
            listView = (ListView) findViewById(R.id.list);
            listViews = (ListView) findViewById(R.id.lists);
            groupsList = new ArrayList<EMGroupInfo>();
            allist = new ArrayList<>();
            alist = new ArrayList<>();
            searchtex = (EditText) findViewById(R.id.query);
            searchBtn = (Button) findViewById(R.id.btn_search);
            View footView = getLayoutInflater().inflate(R.layout.em_listview_footer_view, listView, false);
            footLoadingLayout = (LinearLayout) footView.findViewById(R.id.loading_layout);
            footLoadingPB = (ProgressBar) footView.findViewById(R.id.loading_bar);
            footLoadingText = (TextView) footView.findViewById(R.id.loading_text);
            listView.addFooterView(footView, null, false);
            footLoadingLayout.setVisibility(View.GONE);

            adapters = new GroupsAdapter(PublicGroupsActivity.this, 1, allist);
            listViews.setAdapter(adapters);
            loadAndShowData();
            //模糊查找
            searchtex.addTextChangedListener(new TextWatcher() {
                  @Override
                  public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                  }

                  @Override
                  public void onTextChanged(CharSequence s, int start, int before, int count) {
                        if (!TextUtils.isEmpty(s.toString())) {
                              allist.clear();
                              for (int i = 0; i < groupsList.size(); i++) {
                                    if (groupsList.get(i).getGroupName().toString().contains(s.toString())) {
                                          allist.add(groupsList.get(i));
                                    }
                                    listView.setVisibility(View.GONE);
                                    listViews.setVisibility(View.VISIBLE);
                                    System.out.println(allist.toString() + "模糊查找" + groupsList.size());
                                    adapters.notifyDataSetChanged();
                              }
                        } else {
                              listView.setVisibility(View.VISIBLE);
                              listViews.setVisibility(View.GONE);
                              System.out.println(allist.toArray().toString() + "模糊查找全部");
                              adapter.notifyDataSetChanged();
                        }
                  }

                  @Override
                  public void afterTextChanged(Editable s) {


                  }
            });


            listView.setOnItemClickListener(new OnItemClickListener() {
                  @Override
                  public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        startActivity(new Intent(PublicGroupsActivity.this, GroupSimpleDetailActivity.class).
                                  putExtra("groupinfo", adapter.getItem(position)));
                  }
            });

            listViews.setOnItemClickListener(new OnItemClickListener() {
                  @Override
                  public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        startActivity(new Intent(PublicGroupsActivity.this, GroupSimpleDetailActivity.class).
                                  putExtra("groupinfo", adapters.getItem(position)));
                  }
            });
            listView.setOnScrollListener(new OnScrollListener() {
                  @Override
                  public void onScrollStateChanged(AbsListView view, int scrollState) {
                        if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
                              if (listView.getCount() != 0) {
                                    int lasPos = view.getLastVisiblePosition();
                                    if (hasMoreData && !isLoading && lasPos == listView.getCount() - 1) {
                                          loadAndShowData();
                                    }
                              }
                        }
                  }

                  @Override
                  public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                  }
            });

      }

      public void search(View view) {
            startActivity(new Intent(this, PublicGroupsSeachActivity.class));
      }

      private void loadAndShowData() {
            new Thread(new Runnable() {
                  public void run() {
                        try {
                              isLoading = true;
                              final EMCursorResult<EMGroupInfo> result = EMClient.getInstance().groupManager().getPublicGroupsFromServer(pagesize, cursor);
                              final List<EMGroupInfo> returnGroups = result.getData();
                              runOnUiThread(new Runnable() {
                                    public void run() {
                                          searchBtn.setVisibility(View.GONE);
                                          groupsList.addAll(returnGroups);
                                          alist.addAll(returnGroups);
                                          if (returnGroups.size() != 0) {
                                                cursor = result.getCursor();
                                                if (returnGroups.size() == pagesize)
                                                      footLoadingLayout.setVisibility(View.VISIBLE);
                                          }
                                          if (isFirstLoading) {
                                                pb.setVisibility(View.INVISIBLE);
                                                isFirstLoading = false;
                                                // allist.addAll(groupsList);
                                                adapter = new GroupsAdapter(PublicGroupsActivity.this, 1, groupsList);
                                                listView.setAdapter(adapter);
                                          } else {
                                                if (returnGroups.size() < pagesize) {
                                                      hasMoreData = false;
                                                      footLoadingLayout.setVisibility(View.VISIBLE);
                                                      footLoadingPB.setVisibility(View.GONE);
                                                      footLoadingText.setText("No more data");
                                                }
                                                adapter.notifyDataSetChanged();
                                          }
                                          isLoading = false;
                                    }
                              });
                        } catch (HyphenateException e) {
                              e.printStackTrace();
                              runOnUiThread(new Runnable() {
                                    public void run() {
                                          isLoading = false;
                                          pb.setVisibility(View.INVISIBLE);
                                          footLoadingLayout.setVisibility(View.GONE);
                                          // Toast.makeText(PublicGroupsActivity.this, "load failed, please check your network or try it later", Toast.LENGTH_SHORT).show();
                                    }
                              });
                        }
                  }
            }).start();
      }

      /**
       * adapter
       */
      private class GroupsAdapter extends ArrayAdapter<EMGroupInfo> {

            private LayoutInflater inflater;

            public GroupsAdapter(Context context, int res, List<EMGroupInfo> groups) {
                  super(context, res, groups);
                  this.inflater = LayoutInflater.from(context);
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                  if (convertView == null) {
                        convertView = inflater.inflate(R.layout.em_row_group, parent, false);
                  }
                  ((TextView) convertView.findViewById(R.id.name)).setText(getItem(position).getGroupName());

                  return convertView;
            }
      }

      public void back(View view) {
            finish();
      }
}
